import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/getParameterServlet")
public class GetParameterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取 query string 键值对. 例如: ?studentId=10&studentName=张三
        String studentId = req.getParameter("studentId");
        String studentName = req.getParameter("studentName");
        String s = req.getQueryString();

        System.out.println(studentId);
        System.out.println(studentName);
        System.out.println(s);

        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(studentId + ": " + studentName + "<br>");
        resp.getWriter().write(s);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 构造 Post 请求, 可以用 postman 也可以用 html.
        // 获取 body 中 重要参数. 例如: ?studentId=10&studentName=张三

        req.setCharacterEncoding("utf8"); // 针对请求设置编码方式.-->告诉 servlet(tomcat)如何解析请求.
        String studentId = req.getParameter("studentId");
        String studentName = req.getParameter("studentName");
        System.out.println(studentId);
        System.out.println(studentName);

        resp.setContentType("text/html; charset=utf8"); // 设置响应的 格式 与 编码方式.--> 告诉浏览器如何解析
        resp.getWriter().write(studentId + ": " + studentName + "<br>");
    }
}
